<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="collegeName" placeholder="请输入院系名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 15px" />
        </div>
        <div class="head-container">
          <el-tree :data="collegeOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>

      <!--学生数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="学号" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入学号" clearable @keyup.enter.native="username" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="name" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="item in statusArray" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['system:student:list']" type="primary" icon="el-icon-search" size="small"
              @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            <el-button v-hasPermi="['system:student:add']" type="primary" plain icon="el-icon-plus" size="small"
              @click="handleAdd">新增</el-button>
            <el-button v-hasPermi="['system:student:delete']" type="danger" plain icon="el-icon-delete" size="small"
              :disabled="multiple" @click="handleDelete">
              批量删除</el-button>
            <el-button v-hasPermi="['system:student:import']" type="info" plain icon="el-icon-upload2" size="small"
              @click="handleImport">导入</el-button>
            <el-button v-hasPermi="['system:student:export']" type="warning" plain icon="el-icon-download" size="small"
              @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column label="学号" align="center" prop="username" />
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="院系" align="center" prop="collegeName" />
          <el-table-column label="手机号" align="center" prop="phoneNumber" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="启用" inactive-value="禁用"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-hasPermi="['system:student:update']" size="mini" type="text" icon="el-icon-edit"
                @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-hasPermi="['system:student:delete']" size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <Pagination v-show="total>0" :total="total" :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学号" prop="username">
              <el-input v-model="form.username" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input :disabled="title=='修改学生'" v-model="form.password" placeholder="请输入密码" type="password"
                show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="院系" prop="collegeId">
              <treeselect v-model="form.collegeId" :options="collegeOptions" :normalizer="normalizer" :show-count="true"
                placeholder="请选择所属院系" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入内容" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="item in sexs" :key="item" :label="item">
                  {{item}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in statusArray" :key="item" :label="item">
                  {{item}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :before-upload="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" :drag="true">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listStudent,
    getStudent,
    deleteStudent,
    addStudent,
    updateStudent
  } from "@/api/system/student";
  import {
    getToken
  } from "@/utils/auth";
  import {
    listCollege
  } from "@/api/system/college";
  import {
    listRole
  } from "@/api/system/role";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Pagination from '@/components/Pagination'

  export default {
    name: "Student",
    components: {
      Treeselect,
      Pagination
    },
    data() {
      return {
        visible: false,
        statusArray: [
          '启用',
          '禁用'
        ],
        sexs: ['男', '女'],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 用户表格数据
        studentList: null,
        // 弹出层标题
        title: "",
        collegeOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 学院名称
        collegeName: undefined,
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "name"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            Authorization: getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/student/import"
        },
        // 查询参数
        queryParams: {
          currentPage: 1,
          pageSize: 10,
          username: undefined,
          name: undefined,
          status: undefined
        },
        // 表单校验
        rules: {
          username: [{
            required: true,
            message: "学号不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "姓名不能为空",
            trigger: "blur"
          }],
          collegeId: [{
            required: true,
            message: "院系不能为空",
            trigger: "change"
          }],
          password: [{
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            required: true,
            trigger: "blur",
            message: "请输入正确格式的邮箱"
          }],
          roleIds: [{
            required: true,
            message: "角色不能为空",
            trigger: "change"
          }]
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      collegeName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getTreeselect();
    },
    methods: {
      /** 查询学生列表 */
      getList() {
        this.loading = true;
        listStudent(this.queryParams).then(response => {
          this.studentList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      /** 转换院系数据结构 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleStatusChange(row) {
        let text = row.status
        this.$confirm('确认要"' + text + '""' + row.name + '"吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStudent(row).then(() => {
            this.getList()
            this.$message.success(text + '成功')
          }).catch(() => {
            this.getList()
          })
        }).catch(() => {
          this.getList()
        })
      },
      /** 查询院系下拉树结构 */
      getTreeselect() {
        listCollege({
          status: '启用'
        }).then(response => {
          this.collegeOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.collegeId = data.id
        this.handleQuery();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.visible = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          collegeId: undefined,
          username: undefined,
          name: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          sex: '男',
          status: '启用',
          remark: undefined,
          roleIds: []
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.currentPage = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$refs.queryForm.resetFields()
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.multiple = !selection.length;
      },
      getRoleList() {
        listRole({
          status: '启用'
        }).then((response) => {
          this.roleOptions = response.data.records
        })
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getTreeselect();
        this.getRoleList();
        this.open = true;
        this.title = "添加学生";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeselect();
        this.getRoleList();
        getStudent(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改学生";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateStudent(this.form).then(response => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addStudent(this.form).then(response => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除ids为"' + ids + '"的数据项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteStudent(ids).then(() => {
            this.getList();
            this.$message.success("删除成功");
          })
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/student/export', {
          ...this.queryParams
        }, `学生表.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "学生导入";
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(file) {
        const suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
        if (suffix != "xls" && suffix != "xlsx") {
          this.$message.error('上传文件只能是xls、xlsx格式');
          return false;
        }
        this.upload.isUploading = true;
        return true;
      },
      // 文件上传成功处理
      handleFileSuccess(response) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .message + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
